package com.nefu.store.tools.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

import java.util.Date;

public class JwtUtils {
    private static final String SALT = "shot";

    public static String createToken(Integer uid, String role) {
        return JWT.create()
                .withClaim("uid", uid)
                .withClaim("role", role)
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24)) // 过期时间一天
                .sign(Algorithm.HMAC256(SALT));
    }

    public static String getUid(String token) {
        return JWT.require(Algorithm.HMAC256(SALT)).build().verify(token).getClaim("uid").asString();
    }

    public static String getRole(String token) {
        return JWT.require(Algorithm.HMAC256(SALT)).build().verify(token).getClaim("role").asString();
    }

    public static boolean verify(String token) {
        try {
            JWT.require(Algorithm.HMAC256(SALT)).build().verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}